<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:20px;float:right">
      <el-button type="primary"  @click="handleCreate">新增账户</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='账户名称' min-width="110" prop="accountName"></el-table-column>
      <el-table-column class-name="status-col" label="员工姓名" min-width="110" align="center" prop="employeeName">
      </el-table-column>
      <el-table-column min-width="80" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.deleted | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="110" align="center" label="创建时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | dateformat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="110">
        <template slot-scope="scope">
          <el-button size="small" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button type="primary" size="small" 
            @click="handeOpreate(scope.row,1)" v-if="scope.row.deleted == 0" 
            :disabled="scope.row.accountName == 'aming'">无效</el-button>
          <el-button type="primary" size="small" 
            @click="handeOpreate(scope.row,0)" v-else>有效</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[5,10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="dialogStatus=='create' ? '新增账户' : '编辑账户'" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="账户名称" label-width="80px" prop="accountName"
          v-if="dialogStatus=='create'">
          <el-input v-model="form.accountName" :maxlength="11"
          placeholder="请输入账户名称（不超过11个字）"></el-input>
        </el-form-item>
        <el-form-item label="账户名称" label-width="80px" prop="accountName"
          v-else>
          <label>{{ form.accountName }}</label>
        </el-form-item>
        <el-form-item label="账户密码" label-width="80px" prop="credentials"
          v-if="dialogStatus=='create'">
          <el-input v-model="form.credentials"
          placeholder="请输入账户密码（至少6个字符）" type="password"></el-input>
        </el-form-item>
        <el-form-item label="账户密码" label-width="80px" prop="password"
          v-else>
          <el-input v-model="form.credentials"
          placeholder="请输入账户密码（至少6个字符）" type="password"></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" label-width="80px" prop="employeeName">
          <el-input v-model="form.employeeName" :maxlength="10"
          placeholder="请输入员工姓名（不超过10个字）"></el-input>
        </el-form-item>
        <el-form-item label="账户权限" label-width="80px" prop="roleIds">
          <el-checkbox-group 
            v-model="roleIds">
            <el-checkbox  border v-for="role in roleList" :label="role.roleId" :key="role.roleId" :checked="role.selected" @change="handleChange(role)" class="checkbox-item">{{role.menuName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getList, add, update, operate, getRoleList, getId } from '@/api/employee'
import NodeRSA from 'node-rsa'

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    return {
      roleIds:[],
      roleList:[],
      dialogStatus:'create',
      form:{
        accountName: '',
        credentials: '',
        employeeName: '',
        roleIds:[],
        remarks: ''
      },
      dialogFormVisible:false,
      list: null,
      total: 0,
      listQuery: {
        pageNo:1,
        pageSize:10
      },
      listLoading: true,
      rules: {
        accountName: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
        credentials: [
          { required: true, message: '请输入账户密码', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validatePass }
        ],
        employeeName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择账户权限', trigger: 'change' }]
      }
    }
  },
  watch:{
    roleIds(val){
      if(!val){ return }
      this.form['roleIds'] = val
    }
  },
  mounted() {
    this.getList()
    this.getRoleList()
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0':'有效',
        '1':'无效'
      }
      return statusMap[status]
    }
  },
  methods: {
    handleChange(row){
      row['selected'] = !row['selected']
    },
    getRoleList() {
      getRoleList().then(response => {
        const { data } = response
        this.roleList = data
      })
    },
    handeOpreate(row, type){
      operate({ 'id':row.id, 'action':type }).then(res => {
        const { code } = res
        if(code == 0){
          this.$notify({
            message: `${type == 1 ? '无效' : '有效'}成功`,
            type: 'success',
            duration: 2000
          })
          row['deleted'] = type
        }
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleCreate() {
      const { list } = this
      if(list.length >= 20){
        this.$message('最多配置20个账户')
        return
      }
      this.roleIds = []
      this.form = {
        accountName: '',
        credentials: '',
        employeeName: '',
        roleIds:[],
        remarks: ''
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      getId({ id:row.id }).then(response => {
        const { code, message, data, data:{ employeesRoleVOList } } = response
        if(code == 0){
          this.form = data
          const roleIds = []
          if(employeesRoleVOList.length != 0){
            employeesRoleVOList.map(e => {
              roleIds.push(e.roleId)
            })
          }
          this.roleIds = roleIds
        }else{
          this.$message(message)
        }
      })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data['list']
        this.total = response.data['total']
        this.listLoading = false
      })
    },
    updateForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form, roleList, form:{ roleIds, credentials } } = this
          const new_ids = []
          if(!credentials){
            form['credentials'] = null
            form['loginTime'] = null
          }else{
            const keyData = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCU+sOs2dwS5k10e44LhAwEVDicF2SM9O6/cDdXuDyemjx/RMT/yDJHQ4+jqJOB11nIdeo2lvrD/9oPMePauTjCaXd7AxO75Gzx24skFOb6Rw5Tvjffgsm0ka+/UbK6OWdruPXJDSCrnRskQVhMNRrV6qGLaOCWCQzNwOcz7aCMQIDAQAB-----END PUBLIC KEY-----'
            const key = new NodeRSA(keyData)
            const time = new Date().getTime()
            key.setOptions({ encryptionScheme: 'pkcs1' })
            const encrypted = key.encrypt(time + credentials, 'base64')
            form['credentials'] = encrypted
            form['loginTime'] = time
          }
          roleList.map(role => {
            roleIds.map(roleIndex => {
              if(roleIndex == role['roleId']){
                new_ids.push(role.parentId)
                new_ids.push(role.roleId)
              }
            })
          })
          form['ids'] = new_ids
          update(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.$notify({
                title: '成功',
                message: '编辑账户成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form, form:{ roleIds, credentials }, roleList } = this
          const new_ids = []
          const keyData = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCU+sOs2dwS5k10e44LhAwEVDicF2SM9O6/cDdXuDyemjx/RMT/yDJHQ4+jqJOB11nIdeo2lvrD/9oPMePauTjCaXd7AxO75Gzx24skFOb6Rw5Tvjffgsm0ka+/UbK6OWdruPXJDSCrnRskQVhMNRrV6qGLaOCWCQzNwOcz7aCMQIDAQAB-----END PUBLIC KEY-----'
          const key = new NodeRSA(keyData)
          const time = new Date().getTime()
          key.setOptions({ encryptionScheme: 'pkcs1' })
          const encrypted = key.encrypt(time + credentials, 'base64')
          form['credentials'] = encrypted
          form['loginTime'] = time
          roleList.map(role => {
            roleIds.map(roleIndex => {
              if(roleIndex == role['roleId']){
                new_ids.push(role.parentId)
                new_ids.push(role.roleId)
              }
            })
          })
          form['ids'] = new_ids
          add(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.$notify({
                title: '成功',
                message: '添加账户成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.pagination-container{
  margin-top:30px;
}
.checkbox-item{
  margin-right:10px;
}
.el-checkbox.is-bordered+.el-checkbox.is-bordered{
  margin-left:0;
}
</style>
